#include <fstream>
#include "headfiles.h"

using namespace std;

int main(int argc, char **argv) {
    if (argc != 3) {
        cout << "Usage: " << argv[0] << " matrix elem" << endl;
        return 0;
    }

    string file_name(argv[1]);
    int elem_num = atoi(argv[2]);

    fstream fs;
    fs.open(file_name.c_str(), fstream::in);
    if (!fs.is_open()) {
        cout << "File " << file_name << " open error!" << endl;
        return 1;
    }

    // matrix dimension
    int m, n;
    string str;
    fs >> str;
    m = atoi(str.c_str());
    fs >> str;
    n = atoi(str.c_str());

    int *matrix;
    matrix = new int[m * n];
    if (matrix == NULL) {
        cout << "Allocate matrix buffer error!" << endl;
        return 1;
    }

    int loc = 0;
    while (fs >> str) {
        if (str.empty()) {
            break;
        }

        matrix[loc] = atoi(str.c_str());
        ++loc;
    }
    fs.close();

    if (loc != m *n) {
        cout << "Incorrect number of elements for matrix!" << endl;
        return 1;
    }

    int index_i, index_j;
    bool ret_code;
    ret_code = searchSortedMatrix1(matrix, m, n, elem_num, index_i, index_j);
    if (ret_code == false) {
        cout << "Elem " << elem_num << " is not found!" << endl;
    }
    else {
        cout << "Index of " << elem_num << " is: (" << index_i << ", " << index_j << ")." << endl;
    }

    ret_code = searchSortedMatrix2(matrix, m, n, elem_num, index_i, index_j);
    if (ret_code == false) {
        cout << "Elem " << elem_num << " is not found!" << endl;
    }
    else {
        cout << "Index of " << elem_num << " is: (" << index_i << ", " << index_j << ")." << endl;
    }

    delete matrix;

    return 0;
}
